package com.ctl.server;

import com.ctl.config.MapBeanConfig;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Slf4j
@Component
@ChannelHandler.Sharable
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    @Autowired
    private MapBeanConfig mapBeanConfig;


    /**
     * 客户端连接会触发
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String id = ctx.channel().id().asLongText();
        log.info("Channel active{}......", id);
        try {
            Object channelHandlerContext = mapBeanConfig.getCtx().get(id);
            if (channelHandlerContext == null) {
                mapBeanConfig.getCtx().putIfAbsent(id, ctx);
            }
        } catch (Exception e) {
            log.error("", e);
        }
    }

    /**
     * 客户端发消息会触发
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String id = ctx.channel().id().asLongText();
        log.info("服务器收到消息:ctx={}, {}", id, msg.toString());
        ctx.write("" + System.currentTimeMillis());
        ctx.flush();

    }

    /**
     * 发生异常触发
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
        log.info("Channel close{}......", ctx.channel().id().asLongText());
    }
}
